<template>
  <div class="app-container">






    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入型号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable
          v-model="queryParams.createTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable
          v-model="queryParams.updateTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建人" prop="createBy">
        <el-input
          v-model="queryParams.createBy"
          placeholder="请输入创建人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新人" prop="updateBy">
        <el-input
          v-model="queryParams.updateBy"
          placeholder="请输入更新人"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['warehouse:good:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['warehouse:good:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['warehouse:good:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['warehouse:good:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="物品ID" align="center" prop="id" />
      <el-table-column label="物品名称" align="center" prop="name" />
      <el-table-column label="型号" align="center" prop="model" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="描述" align="center" prop="description" />

      <el-table-column prop="fileInfoList" label="附件" align="center">
          <template #default="scope">
            <div v-for="file in scope.row.fileInfoList" :key="file.id">


                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    :content="file.fileName"
                    placement="right-start"
                  >
                          <el-link icon="Document" target="#" @click.prevent="handleDownloadWithDialog(file)"
                            >{{ file.fileName }}
                          </el-link>
                  </el-tooltip>

            </div>
          </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="更新人" align="center" prop="updateBy" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['warehouse:good:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['warehouse:good:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入物品名称" />
        </el-form-item>



            <el-form-item label="分类">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" ></el-option>
              </el-select>
            </el-form-item>

        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>

        <!-- 文件上传，无需表单校验所以不需要el-form-item 的 prop="file" -->
        <el-form-item label="上传">
          <!-- action配置#表示后台去处理要访问url，ruoyi必须写v-model -->
            <el-upload ref="file" v-model:file-list="newFileInfoList" action="#" :auto-upload="false" multiple
              :before-upload="fileBeforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :limit="10"
              :on-exceed="handleExceed"
              >
              <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传不超过 20MB 的文件</div>
            </el-upload>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>





  <!-- 下载弹窗 -->
  <el-dialog
    v-model="downloadDialogVisible"
    width="200"
    :show-close="false"
    :close-on-click-modal="false"
    class="download-dialog"
  >
    <div class="download-status">
      <el-icon class="is-loading" :size="20">
        <Loading />
      </el-icon>
    </div>
  </el-dialog>
  <iframe v-show="false" name="download-iframe"></iframe>











  </div>
</template>

<script setup name="Good">
//import XXX from 'path'​ 只能用于导入 export default 的内容。
import {API_GOOD} from "@/api/warehouse/good"
import { usePlugins } from '@/plugins'

const plugins = usePlugins()
const { proxy } = getCurrentInstance()
import { Plus } from '@element-plus/icons-vue'


const goodList = ref([])
const categoryOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    model: null,
    categoryId: null,
    quantity: null,
    description: null,
    enabled: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询【请填写功能名称】列表 */
function getList() {
  loading.value = true
  API_GOOD.list(queryParams.value).then(response => {
    goodList.value = response.rows
    console.log('good',goodList.value)
    total.value = response.total
    loading.value = false
  })

  
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    model: null,
    categoryId: null,
    quantity: null,
    description: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
    categoryName:null,
    fileInfoList:null
  }
  proxy.resetForm("goodRef")
  //重置要删除的文件id
  removeFileIds.value = []
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)

  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加物品"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  //row.id就是点击行修改，ids.value就是勾选的行点上面的修改
  const _id = row.id || ids.value
  API_GOOD.getInfo(_id).then(response => {
    categoryOptions.value = response.categoryList
    form.value = response.data
    open.value = true
    title.value = "修改物品"
    
    //文件列表格式化，标记状态,此时属于打开修改弹窗，显示文件列表，当上传新的文件时，就会更新newFileInfoList.value，到时点击提交按钮时需要对文件进行过滤，只上传新的并传入要删除的
    newFileInfoList.value = convertToUploadFiles(response.data.fileInfoList)
    
    
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["goodRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        newFileInfoList.value = newFileInfoList.value.filter((file) => file.status !== 'success') //拿到未上传的文件
        form.value.fileInfoList = null //更新时无需传递这个
        API_GOOD.editAndUpload(form.value,removeFileIds.value,newFileInfoList.value).then(response => {
          plugins.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        API_GOOD.addAndUpload(form.value,newFileInfoList.value).then(response => {
          plugins.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  
  
  //const _ids =  row.id || ids.value
  const _ids = (row.id != null) ? [row.id] : ids.value
  plugins.$modal.confirm('是否确认删除编号为"' + _ids + '"的数据项？').then(function() {
    return API_GOOD.remove(_ids)
  }).then(() => {
    getList()
    plugins.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('warehouse/good/export', {
    ...queryParams.value
  }, `good_${new Date().getTime()}.xlsx`)
}

getList()




//对应文件列表
const newFileInfoList = ref([])
const removeFileIds = ref([]) //更新记录时要删除的文件
const handleRemove = (file) => {
  //file 是移除的
  //uploadFiles是移除后的数组

  //console.log('file', file)

  if (form.value.id != null) {
    removeFileIds.value.push(file.uid.toString())
  }

}

const handlePreview =  (uploadFile) => {
  console.log(uploadFile)
}

const handleExceed = (files, uploadFiles) => {
  ElMessage.warning(
    `最多10个, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`,
  )
}




/**
 * 用sucess标记已经上传过的文件，将附件数据转换为element
 * @param fileInfoList good的fileInfoList属性
 */
const convertToUploadFiles = (fileInfoList) => {

  return fileInfoList.map((file) => ({
    name: file.fileName,
    url: file.preSignUrl,
    status: 'success', // 由于是从数据库获取，所以是成功状态
    uid: file.id, 
  }))
}

/**
 * @name: 上传之前的文件判断
 * @description: 上传之前的文件判断，判断文件大小文件类型等
 * @param {*} file
 * @return {*}
 */
function fileBeforeUpload(file) {
  let isRightSize = file.size / 1024 / 1024 < 20
  if (!isRightSize) {
    plugins.$modal.msgError('单个文件大小不能超过20MB')
  }
  return isRightSize
}









//下载
const downloadDialogVisible = ref(false)

const handleDownloadWithDialog = async (fileInfo) => {
  try {
    //从 response 对象中提取 data 属性
    //downloadUrl 表示将 data 重命名为 downloadUrl 变量
    const { data: downloadUrl } = await API_GOOD.downloadByUrl(fileInfo)
    if (downloadUrl === null || downloadUrl == '') {
      return
    }

    // 创建隐藏表单（兼容性方案）
    downloadDialogVisible.value = true
    const downloadA = document.createElement('a')
    downloadA.style.display = 'none'
    downloadA.href = downloadUrl
    downloadA.target = 'download-iframe' // 指定iframe名称
    document.body.appendChild(downloadA)
    downloadA.click()

    // 延迟提交确保弹窗关闭
    setTimeout(() => {
      document.body.removeChild(downloadA)
      downloadDialogVisible.value = false
    }, 300)
  } catch (error) {
    downloadDialogVisible.value = false
    console.error('下载失败:', error)
  }
}







</script>
